package com.louis.web.controller;

import java.io.Serializable;

import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.NativeWebRequest;

import com.louis.util.ChangeCaseUtil;
import com.louis.util.DataTypeConverterUtil;

public abstract class FormController<T> extends AbstractController<T> {

	private String				formView;
	private static final String	MODELATTRIBUTE	= "domainObject";

	public FormController() {
		String name = ChangeCaseUtil.firstCharacterLowerCase(getClazz().getSimpleName());
		this.formView = name + "/" + name + "form";
		setRedirectPath("/" + name + "/" + "list");
	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		registerPropertyEditor(binder);
	}

	public void registerPropertyEditor(WebDataBinder binder) {
	}

	@ModelAttribute(MODELATTRIBUTE)
	public T getDomainObject(NativeWebRequest nativeWebRequest) {
		setNativeWebRequest(nativeWebRequest);
		Serializable id = DataTypeConverterUtil.parseInt(getPathVariable("id"), 0);
		return getDomainObject(id);
	}

	@RequestMapping(value = { "/form" + SUFFIX, "/form/{id}" + SUFFIX }, method = RequestMethod.GET)
	public String setupForm(ModelMap model) {
		dataPrepare(model);
		return formView;
	}

	@RequestMapping(value = { "/form" + SUFFIX, "/form/{id}" + SUFFIX }, method = RequestMethod.POST)
	public String save(@ModelAttribute(MODELATTRIBUTE) T domainObject) {
		return redirect();
	}

	@RequestMapping(value = "/delete/{id}" + SUFFIX)
	public String delete() {
		return redirect();
	}

	public void saveBefore(T domainObject) {
	}

	public void saveAfter(T domainObject) {
	}

	public void deleteAfter() {
	}

	public void deleteBefore(T domainObject) {
	}

	public String getFormView() {
		return formView;
	}

	public void setFormView(String formView) {
		this.formView = formView;
	}

	public T getDomainObject(Serializable id) {
		T t = null;
		if (id != null) {
			// t = getGeneralDao().get(id, getClazz());
		}
		if (t == null) {
			try {
				t = getClazz().newInstance();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return t;
	}

}
